package com.hty.accountbook;

import android.Manifest;
import android.app.Activity;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.reflect.Field;

public class UserActivity extends Activity {
    static File dir;
    ListView listView;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "HTYAccountBook";
        dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        setContentView(R.layout.activity_user);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.e(Thread.currentThread().getStackTrace()[2] + "", "checkSelfPermission: " + checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE));
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }

        listView = (ListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String uid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                String username = ((TextView) view.findViewById(R.id.textView_username)).getText().toString();
                Intent intent = new Intent(UserActivity.this, MainActivity.class);
                intent.putExtra("uid", uid);
                intent.putExtra("username", username);
                startActivity(intent);
            }
        });
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
                menu.add(0, 0, 0, "修改用户名");
                menu.add(0, 1, 1, "删除用户");
            }
        });

        getUsers();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "添加用户");
        menu.add(0, 1, 1, "软件目录");
        menu.add(0, 2, 2, "更新日志");
        menu.add(0, 3, 3, "关于");
        menu.add(0, 4, 4, "退出");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                final EditText editText = new EditText(this);
                new AlertDialog.Builder(this).setTitle("新用户名")
                        .setIcon(android.R.drawable.ic_input_add)
                        .setView(editText)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                DBHelper dbHelper = new DBHelper(getApplicationContext());
                                ContentValues values = new ContentValues();
                                values.put("userName", editText.getText().toString());
                                long r = dbHelper.addUser(values);
                                if (r == -1) {
                                    Toast.makeText(getApplicationContext(), "新建用户失败！", Toast.LENGTH_SHORT).show();
                                } else {
                                    getUsers();
                                }
                            }
                        })
                        .setNegativeButton("取消", null).show();
                break;
            case 1:
                //崩溃
//                Intent intent = new Intent();
//                intent.setAction(android.content.Intent.ACTION_VIEW);
//                intent.setDataAndType(Uri.fromFile(dir), "inode/directory");
//                startActivity(intent);
                Toast.makeText(getApplicationContext(), dir.getPath(), Toast.LENGTH_SHORT).show();
                break;
            case 2:
                new AlertDialog.Builder(this)
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("更新日志")
                        .setMessage("V2.4 (2022-01)\n1.标题和导出增加搜索词。\n\nV2.3 (2021-12)\n1.解决添加、修改条目后输入法不消失问题。\n\nV2.2 (2021-04)\n1.优化生成HTML的排版。\n2.生成文件后刷新媒体库。\n\nV2.1 (2020-12)\n修复添加、修改、删除后不按搜索栏关键字过滤问题。\n\nV2.0 (2020-11)\n支持多用户。\n\nV1.0 (2020-10)\n账目的显示、添加、搜索、年份查询 + 收支查询，导出HTML、CSV。")
                        .setPositiveButton("确定", null).show();
                break;
            case 3:
                new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("海天鹰记账本 V2.4")
                        .setMessage("多用户账目的显示、添加、搜索、年份查询 + 收支查询，导出HTML、CSV。\n作者：海天鹰\nQQ：84429027")
                        .setPositiveButton("确定", null).show();
                break;
            case 4:
                finish();
                break;
        }
        return true;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final String sid = ((TextView) menuInfo.targetView.findViewById(R.id.textView_id)).getText().toString();
        final String username = ((TextView) menuInfo.targetView.findViewById(R.id.textView_username)).getText().toString();
        final int position = menuInfo.position;
        switch (item.getItemId()) {
            case 0:
                final EditText editText = new EditText(UserActivity.this);
                editText.setText(username);
                AlertDialog.Builder builder = new AlertDialog.Builder(UserActivity.this);
                builder.setIcon(android.R.drawable.ic_menu_edit);
                builder.setTitle("修改用户名");
                builder.setView(editText);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String username1 = editText.getText().toString();
                        Field field = null;
                        try {
                            //通过反射获取dialog中的私有属性mShowing
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);//设置该属性可以访问
                        } catch (Exception e) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                        }
                        if (!username1.equals("")) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", sid + " -> "+ username1);
                            DBHelper dbHelper = new DBHelper(getApplicationContext());
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("userName", username1);
                            db.update("users", values, "_id = " + sid, null);
                            getUsers();
                            listView.setSelection(position);
                            try {
                                //关闭
                                field.set(dialog, true);
                                dialog.dismiss();
                            } catch (Exception e) {
                                Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                            }
                        } else {
                            editText.setError("用户名不能为空！");
                            try {
                                //设置dialog不可关闭
                                field.set(dialog, false);
                                dialog.dismiss();
                            } catch (Exception e) {
                                Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                            }
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.create().show();
                break;
            case 1:
                builder = new AlertDialog.Builder(UserActivity.this);
                builder.setIcon(android.R.drawable.stat_sys_warning);
                builder.setTitle("删除用户");
                builder.setMessage("此操作将删除用户及其账目，且不可恢复，确定删除用户\n" + username + "?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DBHelper dbHelper = new DBHelper(getApplicationContext());
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        db.delete("users", "_id = " + sid, null);
                        db.execSQL("DROP TABLE account" + sid);
                        getUsers();
                    }
                });
                builder.setNegativeButton("否", null);
                builder.create().show();
                break;
        }
        return true;
    }

    void getUsers() {
        DBHelper helper = new DBHelper(this);
        Cursor cursor = helper.getUsers();
        int count = cursor.getCount();
        setTitle("账本用户" + count);
        String[] from = { "_id", "userName" };
        int[] to = { R.id.textView_id, R.id.textView_username };
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_user, cursor, from, to, 0);
        listView.setAdapter(adapter);
        helper.close();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.e(Thread.currentThread().getStackTrace()[2] + "", permissions[i] + ": " + grantResults[i]);
            }
        }
    }

}